const app = getApp()
import {
  userInfo,
  orderAll,
  orderRob,
  orderMy,
  robClick,
  workCate,
  confirmWork,
  revokeExamine,
  workStart,
  offerPrice,
  workFinish
} from "../../config/https";
//个人中心、订单中心、我抢的单、我下的单、点击抢单、工种分类、用户确认师傅开工、用户撤销审核/停止招标、师傅确认开工、师傅立即报价/师傅修改报价、师傅确认完工
import areaList from '../../config/area.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    myWorkType: '', //我的工种名称
    longitude: '', //经度
    latitude: '', //纬度
    orderList: [],
    page: 0,
    pagesize: 10,
    firstShow: 1, // 第1级tab切换选中
    twoShow: 1, // 第2级tab切换选中
    showOrder: true, // 订单中心 || （我下的单与我抢的单）2级切换
    orderid: '', //订单id
    servicePhone: '', //客服电话
    provinceShow: false,
    showOffer: false, //报价弹窗
    offerType: true, //报价弹窗切换
    newPrice: '', //一开始填的报价 || 修改的价格
    isStartWork: '', //是否确认开工
    oldPrice: '', //原价
    areaList: areaList,
    city: '请选择', //选中的城市
    address: '', //选中的省市
    maskShow: false,
    typeVal: '工种',
    workId: '', //选中的工种id
    columns: '',
    workType: '', //工种类型
    count1: '',
    count2: '',
    count3: ''
  },
  // 第1级切换
  orderClick(e) {
    let type = e.currentTarget.dataset.type
    if (type != 1 && !wx.getStorageSync('token')) {
      wx.navigateTo({
        url: '/pages/logs/logs',
      })
      return
    }
    this.setData({
      firstShow: type,
      twoShow: 1
    })
    this.updateData()
  },
  // 第2级切换
  twoClick(e) {
    let type = e.currentTarget.dataset.type
    let firstShow = this.data.firstShow
    this.setData({
      twoShow: type,
      orderList: [],
      page: 0
    })
    if (firstShow == 2) {
      this.getOrderMy()
    } else {
      this.getOrderRob()
    }
  },
  goAddress(e) {
    let {
      latitude,
      longitude
    } = e.currentTarget.dataset
    console.log(latitude, longitude)
    wx.openLocation({
      latitude: Number(latitude),
      longitude: Number(longitude)
    })
  },
  //省市弹窗
  getProvince() {
    this.setData({
      adcode: app.globalData.adcode,
      provinceShow: true
    })
  },
  //关闭省市弹窗
  provinceClose() {
    this.setData({
      provinceShow: false
    })
  },
  //获取省市
  confirmProvince(e) {
    console.log(e)
    let city = e.detail.values[1].name
    let address = e.detail.values[0].name + e.detail.values[1].name
    this.setData({
      city,
      address
    })
    app.getcoordinate(address).then(res => {
      this.setData({
        longitude: res.location.lng, //经度
        latitude: res.location.lat //纬度
      })
      this.updateData()
    })
    this.provinceClose()
  },
  //获取工种
  getWorkType() {
    workCate().then(res => {
      if (res.code == 1) {
        let workType = res.data
        let newArr = workType.map(item => {
          return item.name
        })
        workType.unshift({
          id: '',
          name: '全部'
        })
        newArr.unshift('全部')
        this.setData({
          columns: newArr,
          workType
        })
      }
    })
  },
  //工种弹窗 || 默认弹窗
  showMask() {
    this.setData({
      maskShow: true
    })
  },
  //关闭工种弹窗 || 关闭默认弹窗
  onClose() {
    this.setData({
      maskShow: false
    })
  },
  //获取选中弹窗值
  confirmClick(e) {
    let index = e.detail.index
    let id = this.data.workType[index].id //工种id
    this.setData({
      typeVal: e.detail.value,
      workId: id
    })
    this.updateData()
    this.onClose()
  },
  //投诉师傅
  goComplaint(e) {
    wx.navigateTo({
      url: '/pages/complaint/complaint?userid=' + e.currentTarget.dataset.userid,
    })
  },
  //抢单中心数据
  getOrderAll() {
    wx.showLoading({
      title: '加载中'
    })
    orderAll({
      longitude: this.data.longitude, //经度
      latitude: this.data.latitude, //纬度
      token: wx.getStorageSync('token'),
      page: ++this.data.page,
      pagesize: this.data.pagesize,
      address: this.data.address,
      work_cate_id: this.data.workId
    }).then(res => {
      wx.hideLoading()
      this.setData({
        orderList: [...this.data.orderList, ...res.data.order],
        servicePhone: res.data.kf_phone,
        count1: res.data.count1,
        count2: res.data.count2,
        count3: res.data.count3
      })
    })
  },
  //我抢的单数据
  getOrderRob() {
    wx.showLoading({
      title: '加载中'
    })
    orderRob({
      token: wx.getStorageSync('token'),
      longitude: this.data.longitude, //经度
      latitude: this.data.latitude, //纬度
      page: ++this.data.page,
      pagesize: this.data.pagesize,
      type: this.data.twoShow //1未施工 2:已施工 3：无效单
    }).then(res => {
      wx.hideLoading()
      this.setData({
        orderList: [...this.data.orderList, ...res.data.order],
        servicePhone: res.data.kf_phone,
        count1: res.data.count1,
        count2: res.data.count2,
        count3: res.data.count3
      })
      console.log(res)
    })
  },
  //我下的单数据
  getOrderMy() {
    wx.showLoading({
      title: '加载中'
    })
    orderMy({
      token: wx.getStorageSync('token'),
      page: ++this.data.page,
      pagesize: this.data.pagesize,
      type: this.data.twoShow //1未施工 2:已施工 3：无效单
    }).then(res => {
      wx.hideLoading()
      this.setData({
        orderList: [...this.data.orderList, ...res.data.order],
        servicePhone: res.data.kf_phone,
        count1: res.data.count1,
        count2: res.data.count2,
        count3: res.data.count3
      })
      console.log(res)
    })
  },
  //用户撤销审核/停止招标
  stopOrder(e) {
    let {
      type,
      orderid
    } = e.currentTarget.dataset
    if (type == 1) {
      wx.navigateTo({
        url: '/pages/revokeOrder/revokeOrder?orderid=' + orderid,
      })
      return
    }
    revokeExamine({
      id: orderid
    }).then(res => {
      app.$tip(res.msg)
      if (res.code == 1) {
        this.updateData()
      }
    })
  },
  //跳转用户评论师傅
  goComment(e) {
    let {
      uid,
      orderid
    } = e.currentTarget.dataset
    wx.navigateTo({
      url: '/pages/userComment/userComment?uid=' + uid + '&orderid=' + orderid,
    })
  },
  //跳转回复谈单情况
  goReply(e) {
    let orderid = e.currentTarget.dataset.orderid
    wx.navigateTo({
      url: '/pages/reply/reply?orderid=' + orderid,
    })
  },
  //订单中心抢单
  robClick(e) {
    let id = e.currentTarget.dataset.id
    if (!wx.getStorageSync('token')) {
      wx.navigateTo({
        url: '/pages/logs/logs',
      })
      return
    }
    if (this.data.isKetubbah == 0) {
      wx.showModal({
        title: '你还未支付平台保证金，暂时无法抢单',
        confirmText: '去支付',
        confirmColor: '#2076F9',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/securityFund/securityFund',
            })
          }
        }
      })
      return
    }
    robClick({
      token: wx.getStorageSync('token'),
      order_id: id
    }).then(res => {
      app.$tip(res.msg)
      if (res.code == 1) {
        this.setData({
          firstShow: 3,
          twoShow: 1
        })
        this.updateData()
      }
    })
  },
  //跳转到订单支付
  goPlay(e) {
    wx.navigateTo({
      url: '/pages/payment/payment?orderid=' + e.currentTarget.dataset.orderid + '&paymentType=1',
    })
  },
  //客服
  customerService() {
    let phone = this.data.servicePhone
    wx.showModal({
      title: phone,
      confirmColor: '#2076F9',
      success(res) {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: phone
          })
        }
      }
    })
  },
  //call师傅电话
  callMaster(e) {
    let phone = e.currentTarget.dataset.phone
    wx.makePhoneCall({
      phoneNumber: phone
    })
  },
  //用户确认师傅开工
  confirStartmWork(e) {
    let {
      userid,
      orderid
    } = e.currentTarget.dataset
    wx.showModal({
      title: '温馨提示',
      content: '是否确认该师傅开工？',
      confirmColor: '#2076F9',
      success(res) {
        if (res.confirm) {
          confirmWork({
            order_id: orderid,
            uid: userid
          }).then(res => {
            app.$tip(res.msg)
          })
        }
      }
    })
  },
  //师傅确认开工
  masterWorkerStart(e) {
    let orderid = e.currentTarget.dataset.orderid
    this.setData({
      orderid,
      showOffer: true,
      offerType: true,
      isStartWork: 1
    })
  },
  //师傅确认完工
  finishWork(e) {
    let orderid = e.currentTarget.dataset.orderid
    let that = this
    wx.showModal({
      title: '温馨提示',
      content: '是否确认已完工该操作不可撤销？',
      confirmColor: '#2076F9',
      success(res) {
        if (res.confirm) {
          workFinish({
            token: wx.getStorageSync('token'),
            order_id: orderid
          }).then(res => {
            app.$tip(res.msg)
            if (res.code == 1) {
              that.updateData()
            }
          })
        }
      }
    })
  },
  //立即报价弹窗 || 修改报价弹窗
  offerMask(e) {
    let {
      type,
      orderid,
      price,
      paystatus
    } = e.currentTarget.dataset
    if (this.data.firstShow != 3) return
    if (this.data.paystatus == 1) return
    if (type == 2) {
      this.setData({
        showOffer: true,
        offerType: false
      })
    }
    this.setData({
      orderid,
      oldPrice: price
    })
  },
  //立即报价取值 || 修改报价取值
  newPrice(e) {
    this.setData({
      newPrice: e.detail.value
    })
  },
  //师傅提交报价或修改报价
  submitPrice() {
    offerPrice({
      token: wx.getStorageSync('token'),
      order_id: this.data.orderid,
      price: this.data.newPrice
    }).then(res => {
      app.$tip(res.msg)
      this.setData({
        showOffer: false
      })
      if (res.code == 1) {
        if (this.data.isStartWork == 1) {
          workStart({
            token: wx.getStorageSync('token'),
            order_id: this.data.orderid
          }).then(res => {
            app.$tip(res.msg)
            if (res.code == 1) {
              this.updateData()
            }
          })
        } else {
          this.updateData()
        }
      }
    })
  },
  offerClose() {
    this.setData({
      showOffer: false
    })
  },
  //获取客户电话
  callPhone(e) {
    let {
      phone,
      type
    } = e.currentTarget.dataset
    let tips = '抢单后需要在两个小时内联系客户并 回复谈单情况，否则将会影响您的职 信分，职信分过低将影响您以后继续接单'
    if (type == 2) {
      tips = '是否拨打用户电话？'
    }
    wx.showModal({
      title: '客户电话',
      content: tips,
      confirmColor: '#2076F9',
      success(res) {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: phone
          })
        }
      }
    })
  },
  getUserInfo() {
    userInfo({
      token: wx.getStorageSync('token')
    }).then(res => {
      if (res.code == 1) {
        this.setData({
          myWorkType: res.data.welcome.work_cate_name,
          userType: res.data.welcome.user_type,
          isKetubbah: res.data.welcome.is_project
        })
      }
    })
  },
  updateData() {
    let firstTab = this.data.firstShow
    this.setData({
      orderList: [],
      page: 0
    })
    if (firstTab == 1) {
      this.getOrderAll()
    } else if (firstTab == 2) {
      this.getOrderMy()
    } else {
      this.getOrderRob()
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getWorkType()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (wx.getStorageSync('token')) {
      this.getUserInfo()
    }
    if (!app.globalData.chkLocation) {
      app.location().then(res => {
        this.setData({
          city: res.address_component.city,
          address: res.address_component.province + res.address_component.city,
          longitude: res.location.lng, //经度
          latitude: res.location.lat //纬度
        })
        this.updateData()
      }).catch(err => {
        wx.switchTab({
          url: '/pages/index/index'
        })
        console.log(err)
      })
    } else {
      this.setData({
        city: app.globalData.city, //经度
        address: app.globalData.address,
        longitude: app.globalData.longitude, //经度
        latitude: app.globalData.latitude //纬度
      })
      this.updateData()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let firstTab = this.data.firstShow
    if (firstTab == 1) {
      this.getOrderAll()
    } else if (firstTab == 2) {
      this.getOrderMy()
    } else {
      this.getOrderRob()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})